from decimal import Decimal
from django.shortcuts import render

# Create your views here.
from django_redis import get_redis_connection
from rest_framework.generics import CreateAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView

from goods.models import SKU
from orders.serializers import OrderSettlementSerializer, SaveOrderSerializer


class OrderSettlementView(APIView):
    permission_classes = [IsAuthenticated]
    """订单结算页面"""

    def get(self, request):
        """获取购物车中勾选的商品信息"""
        user = request.user

        # 从购物车中获取用户勾选要结算的商品信息
        redis_conn = get_redis_connection('cart')
        redis_cart = redis_conn.hgetall('cart_%s' % user.id)
        cart_selected = redis_conn.smembers('cart_selected_%s' % user.id)

        cart = {}  # 临时定义的字典，存储所有勾选订单的sku_id 和数量
        for sku_id in cart_selected:
            # cart = {商品sku_id1: 商品数量, 商品sku_id1: 商品数量}
            # 因为redis保存数据的都是bytes类型，所以要类型转换
            # 因为数量都是数值，所以可以通过int转换，如果是字符串则需要　decode
            cart[int(sku_id)] = int(redis_cart[sku_id])

        # 运费
        freight = Decimal('10.00')

        # 经过上面的循环以后，cart里面保存的商品就是已经勾选状态为True的商品列表
        skus = SKU.objects.filter(id__in=cart.keys())

        # 查询商品信息,记录已选商品的数量　和序列化器的商品数量一致
        for sku in skus:
            sku.count = cart[sku.id]

        serializer = OrderSettlementSerializer({'freight': freight, 'skus': skus})
        return Response(serializer.data)

# 保存订单的视图
class SaveOrderView(CreateAPIView):
    """
    保存订单
    """
    permission_classes = [IsAuthenticated]
    serializer_class = SaveOrderSerializer



